import { changeUserPasswordApi } from '@/api/sys/organization'
import AekForm from '@/components/AekForm'
import AekModal, { PromiseThen } from '@/components/AekModal'
import { message } from '@/utils/antdHelper'
import { REGEXP_PASSWORD } from '@/utils/constants'
import { getBasicFn } from '@/utils/dvaUtil'
import { requestWithTry } from '@/utils/request'

const EditModal = () => {
  const { toAction } = getBasicFn({ namespace: 'app' })
  const [form] = AekForm.useForm()

  /** @type {import("@/components/AekForm").FormDataProps[]} */
  const formData = [
    {
      field: 'oldPassword',
      label: '旧密码',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: { name: 'InputPassword' },
    },
    {
      field: 'newPassword',
      label: '新密码',
      formItemProps: {
        rules: [
          { required: true },
          {
            pattern: REGEXP_PASSWORD,
            message: '6-16位，大、小写字母、数字、特殊字符（,.-+_@!?#*%）任意三种类型组合',
          },
        ],
      },
      component: { name: 'InputPassword' },
    },
    {
      field: 'confirmPassword',
      label: '确认密码',
      formItemProps: {
        rules: [
          { required: true },
          {
            pattern: REGEXP_PASSWORD,
            message: '6-16位，大、小写字母、数字、特殊字符（,.-+_@!?#*%）任意三种类型组合',
          },
        ],
      },
      component: { name: 'InputPassword' },
    },
  ]

  const onOk = async () => {
    const values = await form.validateFields()
    if (values.newPassword !== values.confirmPassword) {
      message.error('两次密码不一致')
      return Promise.reject()
    }
    const params = {
      oldPassword: values.oldPassword,
      newPassword: values.newPassword,
    }
    await requestWithTry(changeUserPasswordApi, params)
    toAction('logout')
  }
  return (
    <AekModal title='修改密码' width={500} onOk={onOk}>
      <AekForm form={form} formData={formData} />
    </AekModal>
  )
}

EditModal.PromiseThen = PromiseThen

export default EditModal
